package com.zhiche.lisa.integration.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.zhiche.lisa.core.enums.IntegrationURIEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.integration.dao.mapper.VehicleStandardModeMapper;
import com.zhiche.lisa.integration.dao.model.ImportLogHistory;
import com.zhiche.lisa.integration.dao.model.PushSubSystem;
import com.zhiche.lisa.integration.dao.model.VehicleStandardMode;
import com.zhiche.lisa.integration.service.IImportLogService;
import com.zhiche.lisa.integration.service.IPushSubSystemService;
import com.zhiche.lisa.integration.service.IVehicleStandardModeService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * OTM车辆标准车型 服务实现类
 * </p>
 *
 * @author zhangkun
 * @since 2018-08-22
 */
@Service
public class VehicleStandardModeServiceImpl extends ServiceImpl<VehicleStandardModeMapper, VehicleStandardMode> implements IVehicleStandardModeService {
    private static final Logger LOGGER = LoggerFactory.getLogger(VehicleStandardModeServiceImpl.class);
    @Autowired
    private IPushSubSystemService pushSubSystemService;

    @Autowired
    private IImportLogService logService;
    /**
     * 通过车型编码查询标准车型数据全部返回
     *
     * @param standardModeCode
     */
    @Override
    public List<VehicleStandardMode> queryAllStandardMode(Map<String, Object> standardModeCode) {
        Wrapper<VehicleStandardMode> ew = buildCondition(standardModeCode);
        return this.selectList(ew);
    }

    /**
     * 通过品牌编码，车系编码查询标准车型数据分页返回
     * 通过车型名称模糊查询标准车型数据分页返回
     *
     * @param page
     */
    @Override
    public Page<VehicleStandardMode> queryStandardModePage(Page<VehicleStandardMode> page) {
        if (page == null) {
            throw new BaseException("分页参数不能为空");
        }
        Map<String, Object> cn = page.getCondition();
        Wrapper<VehicleStandardMode> ew = buildCondition(cn);
        List<VehicleStandardMode> standardMode = baseMapper.selectPage(page, ew);
        page.setRecords(standardMode);
        return page;
    }

    /**
     * 通过品牌编码，车系编码查询标准车型数据不分页返回
     * 通过车型名称模糊查询标准车型数据不分页返回
     *
     * @param condition
     */
    @Override
    public List<VehicleStandardMode> queryStandardModeList(Map<String, Object> condition) {
        Wrapper<VehicleStandardMode> ew = buildCondition(condition);
        List<VehicleStandardMode> standardModes = baseMapper.selectList(ew);
        return standardModes;
    }

    private Wrapper<VehicleStandardMode> buildCondition(Map<String, Object> condition) {
        Wrapper<VehicleStandardMode> ew = new EntityWrapper<>();
        if (!Objects.isNull(condition) && !condition.isEmpty()) {
            // 车型编码查询
            if (condition.containsKey("code") && Objects.nonNull(condition.get("code"))) {
                ew.eq("code", condition.get("code").toString());
            }
            //品牌编码查询
            Object vehicleBrandCode = condition.get("vehicleBrandCode");
            if (vehicleBrandCode != null && StringUtils.isNotBlank(vehicleBrandCode.toString())) {
                ew.eq("vehicle_brand_code", vehicleBrandCode.toString());
            }
            //车系编码查询
            Object vehicleClassCode = condition.get("vehicleClassCode");
            if (vehicleClassCode != null && StringUtils.isNotBlank(vehicleClassCode.toString())) {
                ew.eq("vehicle_class_code", vehicleClassCode.toString());
            }
            //车型名称模糊查询
            Object standardModeName = condition.get("name");
            if (standardModeName != null && StringUtils.isNotBlank(standardModeName.toString())) {
                ew.like("name", standardModeName.toString());
            }
            //车型名称模糊查询
            if (condition.containsKey("vehicleName") && StringUtils.isNotBlank(condition.get("vehicleName").toString())){
                ew.like("name", condition.get("vehicleName").toString());
            }
            //车型状态过滤查询
            if (condition.containsKey("status") && StringUtils.isNotBlank(condition.get("status").toString())) {
                ew.eq("status", condition.get("status").toString());
            }
            //时间过滤，查询该时间点后的数据
            if (condition.containsKey("timeAfter") && StringUtils.isNotBlank(condition.get("timeAfter").toString())) {
                ew.ge("gmt_modified", new Date(Long.valueOf(condition.get("timeAfter").toString())));
            }
        }
        return ew;
    }

    @Override
    public  Page<VehicleStandardMode> queryVehicleModelInfo (Page<VehicleStandardMode> page) {
        Map<String, Object> condition = page.getCondition();
        Wrapper<VehicleStandardMode> vehicleStandardModeWrapper = new EntityWrapper<>();
        vehicleStandardModeWrapper.eq("status", "1");
        vehicleStandardModeWrapper.like("vehicle_class_code","江铃改装厂");
        if (Objects.nonNull(condition)) {
            if (Objects.nonNull(condition.get("name")) && StringUtils.isNotEmpty((String) condition.get("name"))) {
                vehicleStandardModeWrapper.like("name", (String) condition.get("name"));
            }
        }
        List<VehicleStandardMode> vehicleStandardModeList = baseMapper.selectPage(page,vehicleStandardModeWrapper);
        page.setRecords(vehicleStandardModeList);
        return page;
    }

    @Override
    public Map<String, Object> modifiedVehicleToOtm (Map<String, String> params) {
        Map<String,Object> result = new HashMap<>();
        //1、组装数据
        if (StringUtils.isEmpty(params.get("orderReleaseXid"))) {
            throw new BaseException(99, "参数【orderReleaseXid】为空");
        }
        if (StringUtils.isEmpty(params.get("vin"))) {
            throw new BaseException(99, "参数【vin】为空");
        }
        if (StringUtils.isEmpty(params.get("stdVechile"))) {
            throw new BaseException(99, "参数【stdVechile】为空");
        }
        Map<String, String> otmParams = new HashMap<>();
        //客户 可不传
        otmParams.put("customer", "");
        //OMS订单号 必传
        otmParams.put("orderReleaseXid", params.get("orderReleaseXid"));
        //车架号 必传
        otmParams.put("vin", params.get("vin"));
        //改装后车型 必传
        otmParams.put("stdVechile", params.get("stdVechile"));
        String otmParam = JSONObject.toJSONString(otmParams);

        //2、导入日志
        this.saveOTMLog(params.get("shipmentGid"),IntegrationURIEnum.UPDATE_VEHICEL.getCode(),otmParam);

        //3、调用OTM
        String logName = "修改车型推送OTM";
        JSONObject jsonObject = this.callOTMMethod(IntegrationURIEnum.UPDATE_VEHICEL.getCode(),otmParam,logName);
        result.put("data",jsonObject);
        return result;
    }

    private JSONObject callOTMMethod (String type, String otmParam, String logName) {
        JSONObject jsonObject = null;
        Wrapper<PushSubSystem> ew = new EntityWrapper<>();
        ew.eq("type", type);
        List<PushSubSystem> pushSubSystems = pushSubSystemService.selectList(ew);
        if (CollectionUtils.isNotEmpty(pushSubSystems)) {
            for (PushSubSystem subSystem : pushSubSystems) {
                String url = subSystem.getUrl();
                Integer socketTimeOut = subSystem.getSocketTimeOut();
                LOGGER.info(logName + "url:{},PARAM:{} result:{}", url, otmParam);
                String result = HttpClientUtil.postJson(url, null, otmParam, socketTimeOut);
                LOGGER.info(logName + " result:{}", result);
                if (StringUtils.isBlank(result)) {
                    throw new BaseException("OTM返回接口为空");
                } else {
                    jsonObject = JSON.parseObject(result);
                    boolean success = jsonObject.getBoolean("success");
                    if (!success) {
                        throw new BaseException(jsonObject.getString("message"));
                    }
                }
            }
        }
        return jsonObject;
    }

    private void saveOTMLog (String shipmentGid,String setType,String otmParam) {
        ImportLogHistory importLogHistory = new ImportLogHistory();
        importLogHistory.setSourceSys("TMS");
        importLogHistory.setSourceKey(shipmentGid);
        importLogHistory.setType(setType);//208
        importLogHistory.setImportStartTime(new Date());
        importLogHistory.setImportEndTime(new Date());
        new Thread(() -> {
            LOGGER.info("modifiedVehicleToOtm开始保存导入日志---------------");
            try {
                logService.saveImportLogToQiniu(importLogHistory, otmParam);
            } catch (Exception e) {
                LOGGER.error("modifiedVehicleToOtm日志保存失败---------------");
            }
            LOGGER.info("modifiedVehicleToOtm完成日志保存---------------");
        }).start();
    }
}
